package com.huwaiwai001.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 歪大哥😁
 * @date 2020-07-07.
 */
public class BIOServer {

    public static void main(String[] args) throws Exception {
        // 线程池
        // 1.创建一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 2.如果客户端连接  就创建一个线程  与之通信
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务端启动了");
        while (true) {
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            executorService.execute(() -> handle(socket));
        }
    }

    private static void handle(Socket socket) {
        try {
            byte[] bytes = new byte[1024];
            // 通过socket 获取输入流
            InputStream inputStream = socket.getInputStream();
            // 循环读取客户端发送的数据
            while (true) {
                int read = inputStream.read(bytes);
                if (read == -1) {
                    break;
                }
                // 输出客户端发送的数据
                System.out.println(new String(bytes, 0, read));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
